package com.qdlc.p2p.dal.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.common.model.jpa.SearchFilter;
import com.qdlc.p2p.dal.dao.ScoreTypeDao;
import com.qdlc.p2p.dal.dto.ScoreType;
import com.qdlc.p2p.dal.model.ScoreTypeModel;

@Repository("scoreTypeDao")
public class ScoreTypeDaoImpl extends BaseDaoImpl<ScoreType> implements ScoreTypeDao {

	@Override
	public ScoreType getScoreTypeByNid(String nid) {
		QueryParam param = QueryParam.getInstance();
		param.addParam("status", 1);
		param.addParam("nid", nid);
		return super.findByCriteriaForUnique(param);
	}

	@Override
	public PageDataList<ScoreTypeModel> scoreRuleList(ScoreTypeModel model) {
		QueryParam param = QueryParam.getInstance().addPage(model.getPage(), model.getRows());
		if (StringUtil.isNotBlank(model.getSearchName()))
			param.addParam("name", SearchFilter.Operators.LIKE, model.getSearchName().trim());
		PageDataList<ScoreType> dataList = this.findPageList(param);
		PageDataList<ScoreTypeModel> modelList = new PageDataList<ScoreTypeModel>();
		List<ScoreTypeModel> list = new ArrayList<ScoreTypeModel>();
		if (null != dataList.getList() && dataList.getList().size() > 0) {
			for (ScoreType entity : dataList.getList()) {
				ScoreTypeModel scoreTypeModel = ScoreTypeModel.instance(entity);
				list.add(scoreTypeModel);
			}
			modelList.setList(list);
		}
		modelList.setPage(dataList.getPage());
		return modelList;
	}

	/**
	 * 开启禁用规则
	 * @param model
	 * @return
	 */
	@Override
	public int toggleStatus(ScoreTypeModel model) {
		String jpql = "update ScoreType set status = :status where id = :id";
		Query query = em.createQuery(jpql);
		query.setParameter("status", model.getStatus());
		query.setParameter("id", model.getId());
		return query.executeUpdate();
	}
}
